<!--
 * @Author: your name
 * @Date: 2020-04-29 16:35:52
 * @LastEditTime: 2020-05-12 13:53:44
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \v1.0.0\pages\work\form_test\form_test.vue
 -->

<template>
	<view>
		<template v-for="(item,index) in jsonData_">
			<component :is="'kmlc-form-'+item.type" :label="item.label" :key="index" :em-data="item" v-model="item.value"
			 @onChangeVal="onChangeVal($event,index)" @submit='submitData' @reset='reset'></component>
		</template>

		<!-- <button type="default" @click='reset'>重置</button>
		<button type="default" @click='submitData'>提交</button> -->

	</view>
</template>

<script>
	const form = require("@/common/framework/libs/formValidation.js")

	import {
		jsonData
	} from './jsonData.js';
	export default {
		data() {
			return {
				jsonData_: {},
				formData: {},
			}
		},
		created() {
			this.jsonData_ = jsonData && jsonData.list;
		},
		methods: {
			onChangeVal(e) {
				// console.log(e);
				// console.log(e.value);
			},
			reset() {
				let changeData = this.jsonData_.map(item => {
					// console.log('value type:')
					// console.log(typeof item.options.defaultValue)
					//排除按钮
					if (item.type == 'button') {
						return item;
					}

					switch (typeof item.options.defaultValue) {
						case 'string':
							item.options.defaultValue = '';
							break;
						case 'number':
							item.options.defaultValue = 0;
							break;
						case 'array':
							item.options.defaultValue = [];
							break;
						case 'object':
							item.options.defaultValue = {};
							break;
					};
					return item;
				});
				this.jsonData_ = JSON.parse(JSON.stringify(changeData)); //重置数据，改变json地址，watch监听
			},

			submitData() {
				//获取默认值，添加到表单数据里
				//构造验证结构
				let rules = this.jsonData_.map(item => {
					//排除按钮
					if (item.type == 'button') {
						return item;
					};
					let {
						rules,
						key
					} = item;
					if (!this.formData[key]) {
						this.formData[key] = item.options.defaultValue;
					};
					return {
						name: item.key,
						rule: rules.map(item => {
							if ('required' in item) {
								return item.required ? 'required' : '';
							} else {
								return item.pattern;
							}
						}),
						msg: rules.map(item => item.message)
					};
				});
				// console.log('this.formData:', this.formData);
				let checkRes = form.validation(this.formData, rules);
				if (!checkRes) {
					// console.log('checkRes:', checkRes);
					uni.showToast({
						title: "验证通过!",
						icon: "none"
					});
				} else {
					uni.showToast({
						title: checkRes,
						icon: "none"
					});
				}
			}
		},
	}
</script>

<style>
	.text_area_class {
		line-height: 35upx;
		width: 95%;
		min-height: 105upx;
		max-height: 175upx;
		border: 1upx solid #F5F5F5;
		overflow: hidden;
	}
</style>
